package miko.mikoplex.model;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class GameBoardModel {
	private char board[][];
	
	public final int width,height;
	public GameBoardModel(int _width,int _height) {
		width = _width;
		height = _height;
		board = new char[width][height];
	}
	
	class Rect {
		int width;
		int height;
	}
	public GameBoardModel(String boardsrc) {
		Rect r = new Rect();
		initByBoardSize(boardsrc,r);
		load(boardsrc);
		width = r.width;
		height = r.height;
	}
	
	public char get(int i,int j) {
		return board[i][j];
	}
	
	public void set(int i,int j,char val) {
		board[i][j] = val;
	}
	
	private void initByBoardSize(String boardsrc,Rect r) {
		int i=0,j=0;
		r.width = 0;
		CharacterIterator it = new StringCharacterIterator(boardsrc);
		for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
			if (ch != '\n' &&
					ch != ' ' &&
					Character.isWhitespace(ch)) continue;
			if (ch == '\n') {
				r.width = Math.max(i, r.width);
				i = 0;
				j++;
			} else {
				i++;
			}
		}
		if (!boardsrc.endsWith("\n")) {
			r.width = Math.max(i, r.width);
			i = 0;
			j++;
		}
		
		r.height = j;
		board = new char[r.width][r.height];
	}
	public void load(String boardsrc) {
		int i=0,j=0;
		CharacterIterator it = new StringCharacterIterator(boardsrc);
		for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
			if (ch == '\n') {
				i = 0;
				j++;
			} else {
				board[i][j] = ch;
				i++;
			}
		}
	}
}
